package com.xtm.exercise.base.B01session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/sessionDemo")
public class SessionDemo extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //使用session共享数据
        //1.获取session
        HttpSession session = request.getSession();
        //2.存储数据
        session.setAttribute("msg","hello session");
        //3.获取数据
        Object msg = session.getAttribute("msg");
        System.out.println(msg);

        //期望客户端关闭后，session也能相同
        Cookie c = new Cookie("JSESSIONID",session.getId());
        c.setMaxAge(60*60);
        response.addCookie(c);

        /**
         * 清除session的方法
         */
//        (1)removeAttribute()方法。该方法是用来删除session对象中保存的指定属性信息。
        session.setAttribute("name", "iverson");session.removeAttribute("name");
//        (2)、invalidate()方法。该方法可以清除session对象中的所有信息。
        session.invalidate();

        Object msginvalidate = session.getAttribute("msg");
        System.out.println(msginvalidate);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
